<template>
  <div class="movies">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="电影名称">
        <el-input
          v-model="formInline.movieName"
          placeholder="电影名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="电影类型">
        <el-input
          v-model="formInline.movieType"
          placeholder="电影类型"
          clearable
        />
      </el-form-item>
      <el-form-item label="电影标签">
        <el-select v-model="formInline.hotnew" placeholder="电影标签" clearable>
          <el-option label="热映中" value="hot" />
          <el-option label="新上架" value="new" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="queryPanel">查询</el-button>
      </el-form-item>
    </el-form>
    <div class="head">
      <div class="left">已上架电影</div>
      <div class="right">
        <el-button
          type="primary"
          icon="el-icon-circle-plus-outline"
          @click="add"
        >上架电影</el-button>
      </div>
    </div>
    <div class="list">
      <el-card v-for="(item, i) in movieList" :key="i" class="box-card">
        <div class="box">
          <!-- <img :src="item.imageUrl" alt="" /> -->
          <div style="width: 160px; height: 220px">
            <el-image
              style="width: 160px; height: 220px"
              :src="item.imageUrl"
              fit="cover"
            >
              <div slot="error" class="image-slot">
                <span>加载失败</span>
              </div>
            </el-image>
          </div>
          <div class="info">
            <div class="title">
              <el-link
                :underline="false"
                style="font-size: 20px"
                type="primary"
              >
                {{ item.name }}
              </el-link>
              <el-tag v-if="item.region === 'hot'" type="danger">
                热映中
              </el-tag>
              <el-tag v-else type="success"> 新上架 </el-tag>
            </div>
            <div class="desc">
              {{ item.desc }}
            </div>
            <div class="type">
              <span>类型：</span>
              <span>{{ item.type.join("、") }}</span>
            </div>
            <div class="pobox">
              <div class="peplon">
                <div class="item">
                  <span>导演：</span> <span>{{ item.dy }}</span>
                </div>
                <div class="item">
                  <span>主演：</span> <span>{{ item.zy }}</span>
                </div>
              </div>
              <div class="operate">
                <el-button
                  v-if="curRole === 'admin'"
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  round
                  @click="edit(item.id)"
                >
                  编辑
                </el-button>
                <el-button
                  v-if="curRole != 'admin'"
                  type="primary"
                  icon="el-icon-tickets"
                  size="mini"
                  round
                  @click="detail(item.id)"
                >
                  详情
                </el-button>
                <el-button
                  v-if="curRole === 'admin'"
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  round
                  @click="remove(item.id)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <el-dialog
      title="上架电影"
      :visible.sync="dialogVisible"
      width="60%"
      top="8vh"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="90px"
        class="demo-ruleForm"
        label-position="left"
        :disabled="disabled"
      >
        <el-form-item label="电影封面">
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :on-change="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="ruleForm.imageUrl"
              :src="ruleForm.imageUrl"
              class="avatar"
            >
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="电影名称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="电影标签" prop="region">
          <el-select v-model="ruleForm.region" placeholder="请选择电影标签">
            <el-option label="热映中" value="hot" />
            <el-option label="新上架" value="new" />
          </el-select>
        </el-form-item>
        <el-form-item label="电影类型" prop="type">
          <el-checkbox-group v-model="ruleForm.type">
            <el-checkbox label="科幻" name="type" />
            <el-checkbox label="动画" name="type" />
            <el-checkbox label="剧情" name="type" />
            <el-checkbox label="战争" name="type" />
            <el-checkbox label="武侠" name="type" />
            <el-checkbox label="古装" name="type" />
            <el-checkbox label="悬疑" name="type" />
            <el-checkbox label="其他" name="type" />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="电影导演" prop="dy">
          <el-input v-model="ruleForm.dy" />
        </el-form-item>
        <el-form-item label="电影主演" prop="zy">
          <el-input v-model="ruleForm.zy" />
        </el-form-item>
        <el-form-item label="电影简介" prop="desc">
          <el-input v-model="ruleForm.desc" rows="3" type="textarea" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          v-if="disabled"
          type="primary"
          @click="close()"
        >关 闭</el-button>
        <el-button v-if="!disabled" @click="close()">取 消</el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          @click="submitForm('ruleForm')"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Movies',
  data() {
    return {
      formInline: {
        movieName: '',
        movieType: '',
        hotnew: ''
      },
      curRole: '',
      isEdit: false,
      disabled: false,
      movieList: [],
      movies: [
        {
          id: '1',
          imageUrl: require('@/icons/image/movie/lldq.jpg'),
          name: '流浪地球2',
          region: 'hot',
          type: ['科幻'],
          dy: '吴京',
          zy: '吴京、刘德华',
          desc: `移山计划：由中国提出，为流浪地球主体计划，计划建造1万座发动机推动地球走向新家园，行星发动机同步网络依赖原本是互联网的地下光纤，是利用网络切片形成的高密级发动机专用网络。
                方舟计划：由美国提出，在地球同步轨道建立“方舟号空间站”，利用空间站带领人类逃离太阳系，即“飞船派”，太空电梯是方舟计划的核心。
                `
        },
        {
          id: '2',
          imageUrl: require('@/icons/image/movie/mjh.jpg'),
          name: '满江红',
          region: 'new',
          type: ['古装', '战争'],
          dy: '张艺谋',
          zy: '沈腾、易烊千玺、张译',
          desc: `张艺谋最新高口碑悬疑喜剧感动热映中，沈腾、易烊千玺、张译、雷佳音、岳云鹏赴局探案有惊有喜，震撼演绎中国式传奇故事！南宋绍兴年间，岳飞死后四年，秦桧率兵与金国会谈。会谈前夜，金国使者死在宰相驻地，所携密信也不翼而飞。小兵张大（沈腾 饰）与亲兵营副统领孙均（易烊千玺 饰）机缘巧合被裹挟进这巨大阴谋之中，宰相秦桧（雷佳音 饰）命两人限一个时辰之内找到凶手。
                `
        }
      ],
      dialogVisible: false,
      ruleForm: {
        id: new Date().getTime(),
        imageUrl: '',
        name: '',
        region: '',
        type: [],
        dy: '',
        zy: '',
        desc: ''
      },
      rules: {
        name: [{ required: true, message: '请输入电影名称', trigger: 'blur' }],
        region: [
          {
            required: true,
            message: '请选择请选择电影标签',
            trigger: 'change'
          }
        ],
        dy: [{ required: true, message: '请输入电影导演', trigger: 'blur' }],
        zy: [{ required: true, message: '请输入电影主演', trigger: 'blur' }],
        type: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一个电影类型',
            trigger: 'change'
          }
        ],
        resource: [
          { required: true, message: '请选择活动资源', trigger: 'change' }
        ],
        desc: [{ required: true, message: '请填写活动形式', trigger: 'blur' }]
      }
    }
  },
  async created() {
    const movieArr = await this.$localStorage.getItem('allMovies')
    console.log(movieArr)
    if (!movieArr) {
      await this.$localStorage.setItem('allMovies', this.movies)
    }
    this.curRole = await this.$localStorage.getItem('curRole')
    this.getMovieList()
  },
  methods: {
    async submitForm(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          // alert("submit!");
          let movieArr = (await this.$localStorage.getItem('allMovies')) || []
          if (this.isEdit) {
            movieArr = movieArr.map((item) => {
              if (item.id === this.ruleForm.id) {
                item = this.ruleForm
              }
              return item
            })
            await this.$localStorage.setItem('allMovies', movieArr)
            this.$message({
              type: 'success',
              message: '修改成功'
            })
          } else {
            movieArr.unshift(this.ruleForm)
            await this.$localStorage.setItem('allMovies', movieArr)
            this.$message({
              type: 'success',
              message: '上架成功'
            })
          }

          this.close()
          this.getMovieList()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleAvatarSuccess(file, fileList) {
      debugger
      // this.ruleForm.imageUrl = URL.createObjectURL(file.raw);
      const fd = new FileReader()
      fd.readAsDataURL(file.raw)
      // 将文件转化为base64格式写入json文件
      fd.onload = () => {
        const keyString = fd.result
          .toString()
          .replace('data:application/x-pkcs12;base64,', '')
        // console.log("keyString", keyString)
        this.ruleForm.imageUrl = keyString
      }
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    async getMovieList() {
      const movieArr = (await this.$localStorage.getItem('allMovies')) || []
      this.movieList = movieArr
    },

    close() {
      this.ruleForm = {
        id: new Date().getTime(),
        imageUrl: '',
        name: '',
        region: '',
        type: [],
        dy: '',
        zy: '',
        desc: ''
      }
      this.dialogVisible = false
      this.disabled = false
      this.isEdit = false
    },
    add() {
      this.dialogVisible = true
    },
    // 编辑
    async edit(id) {
      const movieArr = (await this.$localStorage.getItem('allMovies')) || []

      const curVal = movieArr.find((item) => item.id === id)
      this.ruleForm = curVal

      this.isEdit = true
      this.dialogVisible = true
    },
    async detail(id) {
      const movieArr = (await this.$localStorage.getItem('allMovies')) || []

      const curVal = movieArr.find((item) => item.id === id)
      this.ruleForm = curVal

      this.disabled = true
      this.dialogVisible = true
    },
    async remove(id) {
      let movieArr = (await this.$localStorage.getItem('allMovies')) || []
      this.$confirm('此操作将删除该电影, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          movieArr = movieArr.filter((item) => {
            return item.id !== id
          })
          await this.$localStorage.setItem('allMovies', movieArr)
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          this.getMovieList()
        })
        .catch(() => {})
    },
    handleClose(done) {
      this.close()
      // done();
    },

    // 查询
    async queryPanel() {
      const movies = await this.$localStorage.getItem('allMovies')

      const { movieName, movieType, hotnew } = this.formInline

      const newMovies = movies.filter((item) => {
        if (
          item.name.includes(movieName) &&
          item.type.join('、').includes(movieType) &&
          item.region.includes(hotnew)
        ) {
          return item
        }
      })

      this.movieList = newMovies
      // console.log(movieName, movieType, hotnew);
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader ::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 148px;
  height: 178px;
  object-fit: cover;
  display: block;
}
.movies {
  padding: 20px 100px;
  ::v-deep .el-input.is-disabled .el-input__inner,
  ::v-deep .el-textarea.is-disabled .el-textarea__inner {
    cursor: default;
  }
  .head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .left {
      font-size: 20px;
      color: #666;
    }
  }
  .list {
    display: flex;
    flex-direction: column;
    gap: 30px;
    padding-top: 30px;
    ::v-deep .el-card__body {
      padding: 0;
    }
    .box {
      display: flex;
      ::v-deep .image-slot {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 160px;
        height: 220px;
        font-size: 14px;
        background: #f5f7fa;
        color: #c0c4cc;
      }
      .info {
        width: 100%;
        padding: 16px 20px 0;
        .title {
          display: flex;
          gap: 20px;

          margin-bottom: 10px;
        }
        .desc {
          height: 78px;
          font-size: 16px;
          line-height: 26px;
          opacity: 0.8;
          overflow: hidden;
        }
        .type {
          margin: 20px 0 10px;
        }
        .pobox {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
        .peplon {
          display: flex;
          gap: 40px;
        }
      }
    }
  }
}
</style>
